const { Config } = require("../models");
const { NotFound } = require("http-errors");
const { Op } = require("sequelize");
let dataResult = {};
// 根据beUsed查询ip配置表
async function ipInfoSingle(beUsed) {
  console.log("beUsed", beUsed);
  if (beUsed) {
    let condition = { where: {} }; // 初始化 condition 对象并包含 where 属性
    condition.where.beUsed = {
      [Op.like]: `%${beUsed}%`,
    };
    const { count, rows } = await Config.findAndCountAll(condition);
    return {
      count,
      rows,
    };
  } else {
    throw new NotFound(`beUsed: ${beUsed}的ip配置表未找到。`);
  }
}

// 获取所有ip配置表
async function getIps(type) {
  const condition = {
    where: {},
  };
  if (type) {
    condition.where.type = type;
  }
  const { count, rows } = await Config.findAndCountAll(condition);
  return {
    count,
    rows,
  };
}
// 查询ip配置表
async function ipForClient(count, rows) {
  const ipListForClient = [];
  for (let i = 0; i < count; i++) {
    const ip = rows[i].dataValues.ip;
    const port = rows[i].dataValues.port;
    const status = rows[i].dataValues.status;
    const type = rows[i].dataValues.type;
    const id = rows[i].dataValues.id;
    const beUsed = rows[i].dataValues.beUsed;
    const ipInfo = {
      id,
      ip,
      port,
      type,
      status,
      beUsed,
    };
    if (ip && port) {
      ipListForClient.push(ipInfo);
    }
  }
  return ipListForClient;
}
async function changeIpStatus(data) {
  // console.log("changIpStatus", data, "dataResult", dataResult);
  // if (!dataResult.hasOwnProperty("status")) {
  //   dataResult = data;
  // } else {
  //   if (dataResult.id == data.id && data.status == dataResult.status) {
  //     return false;
  //   }
  // }

  try {
    const configDetail = await getConfig(data.id);
    const body = await filterBody(data);
    await configDetail.update(body);
    return true;
  } catch (error) {
    return false;
  }
}

async function filterBody(data) {
  return {
    ip: data.ip,
    port: data.port,
    status: data.status,
    type: data.type,
    beUsed: data.beUsed,
  };
}
async function getConfig(id) {
  const configDetail = await Config.findByPk(id);
  if (!configDetail) {
    throw new NotFound(`ID: ${id}的ip配置表未找到。`);
  }
  return configDetail;
}

// 恢复ip配置表 将状态改成未连接状态
async function initIp(type) {
  const { count, rows } = await getIps(type);
  if (count === 0) {
    return false;
  }

  for (let i = 0; i < count; i++) {
    const configDetail = await getConfig(rows[i].dataValues.id);
    const body = await filterBody(rows[i].dataValues);
    body.status = "0";
    await configDetail.update(body);
  }
  return true;
}

module.exports = {
  initIp,
  ipInfoSingle,
  ipForClient,
  getIps,
  changeIpStatus,
};
